<?php

namespace App\Console\Commands;

use App\Console\Commands\Common\CommonCommand;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class ResultSeeLog extends CommonCommand {

    public $signature = 'resseelog';

    public function handle() {

        $days = [];
        foreach (range(0, 10) as $day) {
           $days[] = date('Y-m-d',strtotime("-$day days"));
        }
        $type = 1;
        $fileName = Arr::first($days).'至'.Arr::last($days).'阅读下载分析结果.txt';
        $f = fopen(public_path("./$fileName"),'a');
        fwrite($f, "--------------------  阅   ---    读 ----------------------\n");
        foreach ($days as $day) {
            $query = "SELECT
	`user`.id,
	`user`.nick_name,
	see_log.DAY,
	see_log.type,
	count( see_log.article_id ) AS seecount
FROM
	`see_log`
	INNER JOIN `user` ON see_log.user_id = `user`.id
WHERE
	see_log.type = $type
	AND see_log.`day` = '".$day."'
GROUP BY
	see_log.user_id
HAVING seecount>10
ORDER BY seecount desc";
            $records = DB::select($query);
            fwrite($f, "    $day ：\n");
            foreach ($records as $record) {
                fwrite($f, "$record->id | $record->nick_name | 阅读数：$record->seecount \n");
            }
            fwrite($f, "\n");
            fwrite($f, "\n");
        }
        //===============================================================================================================
        $type = 2;
        fwrite($f, "\n");
        fwrite($f, "\n");
        fwrite($f, "--------------------  下   ---    载 ----------------------\n");
        foreach ($days as $day) {
            $query = "SELECT
	`user`.id,
	`user`.nick_name,
	see_log.DAY,
	see_log.type,
	count( see_log.article_id ) AS seecount
FROM
	`see_log`
	INNER JOIN `user` ON see_log.user_id = `user`.id
WHERE
	see_log.type = $type
	AND see_log.`day` = '".$day."'
GROUP BY
	see_log.user_id
HAVING seecount>10
ORDER BY seecount desc";
            $records = DB::select($query);
            fwrite($f, "    $day ：\n");
            foreach ($records as $record) {
                fwrite($f, "$record->id | $record->nick_name | 下载数：$record->seecount \n");
            }
            fwrite($f, "\n");
            fwrite($f, "\n");
        }

        fclose($f);
        echo $fileName;

    }

}
